import { API_BASE_URL } from "../constants/api";
import { KEY_TOKEN } from "../constants/storage";

/**
 * 微信小程序网络请求封装库
 * 功能：Promise化、全局Loading、自动携带Token、统一错误处理
 */

// const app = getApp(); // 获取应用实例

const CONFIG = {
  BASE_URL: API_BASE_URL,
  DEFAULT_HEADER: {
    "Content-Type": "application/json",
    // apikey: SUPABASE_ANON_KEY, // 使用CONFIG.API_KEY
  },
};

function getAuthHeader() {
  // 获取本地存储的Token（例如用户登录后获取的JWT）
  const token = wx.getStorageSync(KEY_TOKEN);
  // 如果没有用户token，则使用anon key作为Authorization头
  const authHeader = {};

  if (token) {
    authHeader.Authorization = `Bearer ${token}`;
  }
  return authHeader;
}

/**
 * 核心请求函数
 * @param {string} url - 请求地址
 * @param {object} options - 请求配置
 * @returns {Promise}
 */
const request = (url, options = {}) => {
  const {
    method = "GET",
    data = {},
    header = {},
    loading = true, // 默认显示loading
    loadingText = "加载中...",
  } = options;

  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (loading) {
      wx.showLoading({
        title: loadingText,
        mask: true,
      });
    }

    const authHeader = getAuthHeader();

    wx.request({
      url: `${CONFIG.BASE_URL}${url}`,
      data,
      method: method.toUpperCase(),
      header: {
        ...CONFIG.DEFAULT_HEADER,
        ...authHeader, // 自动携带Token
        ...header, // 允许单个请求覆盖默认头
      },
      success: (res) => {
        // console.log("==req==", res);
        switch (res.statusCode) {
          case 401: {
            // Token失效或未认证，引导用户重新登录
            handleAuthError();
            reject(new Error("身份认证失败，请重新登录"));
            break;
          }
          default:
            resolve(res.data);
        }
      },
      fail: (err) => {
        // 网络连接失败等
        wx.showToast({
          title: "网络连接失败，请检查网络",
          icon: "none",
        });
        reject(err);
      },
      complete: () => {
        // 隐藏加载提示
        if (loading) {
          wx.hideLoading();
        }
      },
    });
  });
};

/**
 * 上传文件
 * @param {*} filePath
 * @param {*} fileName
 * @param {*} formData
 * @returns
 */
const uploadFile = (filePath, options = {}) => {
  return new Promise((resolve, reject) => {
    const { fileName = "file", formData, loading = true } = options;
    if (loading) {
      wx.showLoading({
        title: "上传中",
        mask: true,
      });
    }
    const authHeader = getAuthHeader();
    wx.uploadFile({
      url: API_BASE_URL + "/file/upload/fishing-spot", // 服务器接口地址
      filePath, // 要上传的文件路径
      name: fileName,
      formData,
      header: {
        "Content-Type": "multipart/form-data",
        ...authHeader,
      },
      success: function (res) {
        // const data = res.data; // 服务器返回的数据
        const originData = JSON.parse(res.data);
        console.log("上传成功：", originData);
        resolve(originData.data);
      },
      fail: function (error) {
        console.log("上传失败：", error);
        reject(error);
      },
      complete: () => {
        // 隐藏加载提示
        if (loading) {
          wx.hideLoading();
        }
      },
    });
  });
};

/**
 * 处理认证错误（如Token失效）
 */
const handleAuthError = () => {
  // 清除本地无效的Token和用户信息
  // wx.removeStorageSync("token");
  // wx.removeStorageSync("userInfo");

  // 显示提示并跳转到登录页
  wx.showModal({
    title: "提示",
    content: "登录状态已过期，请重新登录",
    showCancel: false,
    success: (res) => {
      if (res.confirm) {
        wx.reLaunch({
          url: "/pages/login/login", // 你的登录页路径
        });
      }
    },
  });
};

// 快捷方法封装
const get = (url, data = {}, options = {}) => {
  return request(url, { method: "GET", data, ...options });
};

const post = (url, data = {}, options = {}) => {
  return request(url, { method: "POST", data, ...options });
};

const put = (url, data = {}, options = {}) => {
  return request(url, { method: "PUT", data, ...options });
};

const del = (url, data = {}, options = {}) => {
  return request(url, { method: "DELETE", data, ...options });
};

// 导出
module.exports = {
  request,
  get,
  post,
  put,
  del,
  uploadFile,
};
